package com.cauli.account.role.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cauli.account.menu.service.RoleMenuService;
import com.cauli.account.role.mapper.RoleMapper;
import com.cauli.account.role.model.dto.RoleVO;
import com.cauli.account.role.model.entity.Role;
import com.cauli.account.role.service.RoleService;
import com.cauli.account.user.service.UserService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Cauli
 * @date 2022-12-13 15:16:02
 * @description 角色 服务实现类
 */
@Service
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {
    @Lazy
    @Autowired
    private UserService userService;

    @Autowired
    private RoleMenuService roleMenuService;

    @Override
    public RoleVO getRoleById(Long roleId) {
        Role role = baseMapper.selectById(roleId);
        RoleVO roleVO = new RoleVO();
        if (role != null) {
            BeanUtils.copyProperties(role, roleVO);
        }
        return roleVO;
    }

    @Override
    public List<RoleVO> getRoleByUserId(Long userId) {
        List<RoleVO> roleList = baseMapper.getRoleList(userId);

        // 服务不对外暴露，网关不传token到子服务，这里通过userId获取session，并设置角色
        String tokenValue = StpUtil.getTokenValueByLoginId(userId);

        // 为这个token在redis中设置角色，使网关获取更方便
        if (StringUtils.isNotEmpty(tokenValue)) {
            if (CollectionUtils.isEmpty(roleList)) {
                StpUtil.getTokenSessionByToken(tokenValue).set("ROLE-LIST", "");
            } else {
                List<String> roleKeyList = roleList.stream().map(RoleVO::getRoleKey).collect(Collectors.toList());
                StpUtil.getTokenSessionByToken(tokenValue).set("ROLE-LIST", roleKeyList);
            }
        }
        return roleList;
    }
}




